package com.example.demo.tool;

import com.example.demo.entity.BaseResponse;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;


public class GenerateTestCase {

    public BaseResponse<String> generateSql(String describe , String content) throws IOException {

        String apiEndpoint= "https://api.openai.com/v1/engines/gpt-3.5-turbo-instruct/completions";

        String apiKey = "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";
        int maxTokens = 1500;

        /*
        System.setProperty("proxyHost", "127.0.0.1"); // 代理的IP地址
        System.setProperty("proxyPort", "33210"); // 代理的端口号
        */

        String ip = "127.0.0.1";
        int port = 7890;

        Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(ip,port));

        //String prompt = "帮我的小狗起个名字。";
        String prompt = describe + "帮我针对" + content + "这道题生成一个测试数据库，给出创建这个数据库的SQL语句，使用postgresql语法，只需要SQL语句，不需要代码注释和说明。";


        System.out.println("主函数");
        System.out.println(prompt);

        URL url = new URL(apiEndpoint);
        HttpURLConnection con = (HttpURLConnection) url.openConnection(proxy);
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer " + apiKey);

        // 设置HTTP请求体
        String requestBody = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": " + maxTokens + "}";
        con.setDoOutput(true);
        con.getOutputStream().write(requestBody.getBytes());

        // 发送HTTP请求并读取响应
        int responseCode = con.getResponseCode();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String response = "";
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response += inputLine;
        }
        in.close();

        System.out.println("88888");
        // 处理响应
        System.out.println("Response code: " + responseCode);
        System.out.println("Response body: " + response);

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(response);

        String sql = jsonNode.get("choices").get(0).get("text").toString();
        sql = sql.substring(1,sql.length()-1);
        sql = sql.replace("\\n" , "\n");
        sql = sql.replace("\\t" , "\t");
        sql = sql.replace("\\" , "\t");

        System.out.println(sql);

        return BaseResponse.success(sql);

    }

}
